package transmissionServer

import (
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"io"
	"log"
	"os"
)

func ScpSend(ReFileName string, ReFileNameAndPath string) {
	// SSH连接配置
	config := &ssh.ClientConfig{
		User: "root",
		Auth: []ssh.AuthMethod{
			//ssh.Password("1qaz"),
			ssh.Password("qwer1234"),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	// 连接SSH服务器
	//SshClient, err := ssh.Dial("tcp", "192.168.0.3:22", config)
	SshClient, err := ssh.Dial("tcp", "192.168.0.30:22", config)
	if err != nil {
		fmt.Println("Failed to connect to SSH server:", err)
		panic(err)
	}
	defer func(SshClient *ssh.Client) {
		err = SshClient.Close()
		PrintErr("SshClient.Close err: ", err)
	}(SshClient)
	// 创建SFTP客户端
	log.Printf("ReFileName :%s ,  ReFileNameAndPath :%s", ReFileName, ReFileNameAndPath)
	//sftpClient, err := sftp.NewClient(SshConn())
	sftpClient, err := sftp.NewClient(SshClient)

	if err != nil {
		fmt.Println("Failed to create SFTP client:", err)
		return
	}
	defer func(sftpClient *sftp.Client) {
		err = sftpClient.Close()
		PrintErr("sftpClient.Close err: ", err)
	}(sftpClient)

	// 打开本地的tar文件
	FileObj, err := os.Open(ReFileNameAndPath)
	if err != nil {
		fmt.Println("Failed to open local tar file: ", err)
		return
	}
	defer func(FileObj *os.File) {
		err = FileObj.Close()
		PrintErr("FileObj.Close err:", err)
	}(FileObj)

	// 在远程主机上创建tar文件
	FileAndPath := fmt.Sprintf("/home/ehminer/test-detect/webserver/%s", ReFileName)
	remoteFile, err := sftpClient.Create(FileAndPath)
	if err != nil {
		fmt.Println("Failed to create remote tar file: ", err)
		return
	}
	defer func(remoteFile *sftp.File) {
		err = remoteFile.Close()
		PrintErr("remoteFile.Close err: ", err)
	}(remoteFile)

	// 将本地tar文件内容复制到远程主机
	_, err = io.Copy(remoteFile, FileObj)
	if err != nil {
		fmt.Println("Failed to copy tar file to remote host: ", err)
		return
	}

	fmt.Println("Tar file sent successfully!")
}

func PrintErr(str string, err error) {
	if err != nil {
		fmt.Println(str, err)
		return
	}
}
